# src/infrastructure/config_manager.py
import pathlib
import yaml
from typing import Any, Dict, Union


class ConfigManager:
    def __init__(self, path: pathlib.Path) -> None:
        self._path = path
        self._data: Dict[str, Any] = {}

    def load(self) -> Dict[str, Any]:
        """读取并解析 YAML 文件

        Returns:
            解析后的 dict: 若文件为空或不存在, 返回空 dict。
        """
        if not self._path.exists():
            return {}
        with self._path.open("r", encoding="utf-8") as f:
            self._data = yaml.safe_load(f) or {}
        return self._data

    def save(self, data: Dict[str, Any]) -> None:
        """将 dict 写入 YAML 文件(覆盖式)

        Args:
            data: 要写入的字典, 支持嵌套
        """
        self._path.parent.mkdir(parents=True, exist_ok=True)
        with self._path.open("w", encoding="utf-8") as f:
            yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
        self._data = data

    def get(self, key: str, default: Any = None) -> Any:
        """点分隔键访问(如 "sgbm.block_size")

        Args:
            key: 点分隔字符串, 如 "camera.fps"
            default: 键不存在时返回的默认值

        Returns:
            对应值或 default
        """
        keys = key.split(".")
        value = self._data
        for k in keys:
            value = value.get(k, default)
            if value is default:
                break
        return value
